package com.csii.activiti.server.core.config;

import cn.hutool.core.util.ReflectUtil;
import com.csii.activiti.server.core.utils.DataSourceUtils;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;

import java.sql.*;
import java.util.List;

@MappedJdbcTypes(JdbcType.ARRAY)
public class ArrayTypeHandler extends BaseTypeHandler {

    private final String reflectKey = "delegate";

    private final String reflectKey1 = "conn";

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {

        if (null != parameter) {
            //兼容多种连接池
            Connection conn = (Connection) ReflectUtil.getFieldValue(ps.getConnection(), reflectKey);
            if (conn == null){
                conn = (Connection) ReflectUtil.getFieldValue(ps.getConnection(), reflectKey1);
            }
            List<String> list = (List<String>) parameter;
            //DataSource source = DataSourceUtils.getDataSource();
            //conn = source.getConnection();

            //conn = DriverManager.getConnection(bean.getUrl(), bean.getUsername(), bean.getPassword());
            //conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.80.5:1521/orcl", "WORKFLOW", "WORKFLOW");
            // TABLES_ARRAY：对应的是在oracle创建的type名，必须大写
            ArrayDescriptor arrayDes = ArrayDescriptor.createDescriptor(DataSourceUtils.getOracleType(), conn);
            //这里是声明一个数据库的数组类型
            ARRAY array = new ARRAY(arrayDes, conn, list.toArray());
            ps.setArray(i, array);
        }
    }

    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return null;
    }

    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return null;
    }

    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
